<template>
    <a-modal :visible="state.visible" :title="modalTitle" @cancel="handleCancel" @ok="handleOk">
        <AForm ref="formRef" :model="state.formData" :labelCol="{ style: 'width:80px' }">
            <AFormItem label="品类名称" name="goodsCategoryName" :rules="[{required:true,message:'必填'}]">
                <AInput v-model:value="state.formData.goodsCategoryName"></AInput>
            </AFormItem>

            <AFormItem label="商品类型" name="type"  :rules="[{required:true,message:'必填'}]">
                <ASelect v-model:value="state.formData.type" >
                    <ASelectOption :value="GoodsTypeEnum.THING">实物</ASelectOption>
                    <ASelectOption :value="GoodsTypeEnum.SERVICE">服务</ASelectOption>
                </ASelect>
            </AFormItem>
        </AForm>
    </a-modal>
</template>
<script lang="ts" setup>
import { ResponseVo, GoodsCategoryTypes, GoodsTypeEnum } from "@/type";
import { reactive, ref, onMounted,computed } from "vue";
import { GoodsCategoryService } from "@/service";
import { message } from "ant-design-vue";
import ARow from "ant-design-vue/lib/grid/Row";

const props = withDefaults(defineProps<{
    currentGoods?: Partial<GoodsCategoryTypes.GoodsCategoryItem>; 
}>(), {
    currentGoods: (): Partial<GoodsCategoryTypes.GoodsCategoryItem> => ({}),
})

const formRef = ref()
const emit = defineEmits<{
    (e: "ok"): void,
    (e: "cancel"): void
}>()

const state = reactive<{
    formData: Partial<GoodsCategoryTypes.GoodsCategoryItem>;
    visible: boolean
}>({
    formData: {},
    visible: true
})

const modalTitle = computed(()=>{
        if(props.currentGoods.goodsCategoryId)return "编辑商品品类";
        if(!props.currentGoods.goodsCategoryId)return "新增商品品类";
    })

onMounted(() => {
    state.formData = { ...props.currentGoods };
})

const handleOk = () => {
    formRef.value.validateFields().then(async (valid: boolean) => {
        if (valid) {
            let res: ResponseVo<any>
            if (state.formData.goodsCategoryId) {
                res = await GoodsCategoryService.editGoodsCategory(state.formData as GoodsCategoryTypes.GoodsCategoryItem);
            } else {
                res = await GoodsCategoryService.addGoodsCategory(state.formData as GoodsCategoryTypes.GoodsCategoryItem);
            }
            if (res.code === 0) {
                message.success("操作成功！")
                emit("ok");
            }
        }
    })
}

const handleCancel = () => {
    emit("cancel")
}
</script>